<template>
    <view class="map">
      <!-- <view class="bar-top" :style="{height:StatusBar+'px'}"></view> -->
        <view class="header w100 flexw" :style="{height:(CustomBar+10)+'px'}">
          <!-- <view v-if="isShow" class="placeholder" :style="{height:(StatusBar+1)+'px'}"></view> -->
            <view class="flex w100">
                <input class="input" @confirm="doneInput" type="text" confirm-type="search" :adjust-position="false" @input="onInput" placeholder="搜索城市 中文/首字母"
                    v-model="searchValue" />
                <view class="back_div fsmall bold blue" @tap="back_city()">
                    取消
                </view>
            </view>
        </view>
        <scroll-view class="w100" scroll-y="true" :scroll-into-view="scrollIntoId" style="height:1000px;">
            <view v-if="disdingwei" id="hot">
                <!-- 定位模块 -->
                <view class="dingwei">
                    <view class="grey flexa fsmall">
                        当前定位
                    </view>
                    <view class="dingwei_city">
                        <button class="dingwei_city_one" :disabled="disabled" @tap="back()">
                            <image class="dw" :src="$imgUrl+'movie/dw.png'" mode=""></image>
                            {{position?position:'定位失败'}}
                        </button>
                        <view class="bold blue fmiddle" @click="getWarpweft">
                            <image v-if="po_tips == '重新定位'" class="refresh" :src="$imgUrl+'movie/refresh.png'" mode=""></image>
                            <text>{{po_tips}}</text>
                        </view>
                    </view>
                </view>
                <!-- 热门 -->
                <view class="dingwei" v-if="hotCity">
                    <view class="grey flexa fsmall">
                        可服务城市
                    </view>
                    <view class="dingwei_city dingwei_city_zuijin">
                        <view class="dingwei_city_one" v-for="(item,index) in hotCity" :key="index" @tap="back_city(item)">
                            {{item.regionName}}
                        </view>
                    </view>
                </view>
                <!-- 可服务 -->
            </view>
            <!-- 城市列表 -->
            <view v-if="searchValue == ''" v-for="(item, index) in list" :id="item.idx" :key="item.idx">
                <view class="letter-header bold">{{ item.idx }}</view>
                <view class="city-div" v-for="(city, i) in item['cities']" :key="i" @tap="back_city(city)">
                    <text class="city">{{ city.regionName }}</text>
                </view>
            </view>
            <!-- 搜索结果 -->
            <view class="city-div" v-for="(item, index) in searchList" :key="index" @tap="back_city(item)">
                <text class="city">{{ item.regionName }}</text>
            </view>
        </scroll-view>
        <!-- 右侧字母 -->
        <view class="letters" id="list" v-if="searchValue == ''" @touchstart="touchStart" @touchmove.stop.prevent="touchMove" @touchend="touchEnd">
            <view class="fmin" v-for="item in letter" :key="item.idx">{{ item.idx }}</view>
        </view>
        <!-- 选中之后字母 -->
        <view class="mask" v-if="touchmove">
            <view class="mask-r bold">{{scrollIntoId}}</view>
        </view>
    </view>
</template>

<script>
const QQMapWX = require('@/utils/tools/qqmap-wx-jssdk.min.js')
var qqmapsdk = new QQMapWX({
    key: 'XX4BZ-INFW4-PZNU7-KKMEQ-HMEYE-AXBQT'
});
export default {
    props: {
        data: {
            type: Object
        },
        cityList: {
            type: Array,
            required: true
        }
        //data.isNational  是否全国 0是1否 
    },
    data() {
        return {
            // StatusBar: this.StatusBar,
            winHeight: 0,
            itemHeight: 0,
            winOffsetY: 0,
            touchmove: false,
            StatusBar: uni.getSystemInfoSync().statusBarHeight,
            scrollHeight: this.statusBarHeight,
            ImgUrl: this.ImgUrl,
            letter: [],
            searchValue: '',
            scrollIntoId: '',
            list: [],
            tId: null,
            searchList: [],
            showMask: false,
            disdingwei: true,
            cacheLocation: '', //最近访问
            position: '', //定位获取的位置
            po_tips: '重新定位',
            hotCity: '',
            disabled: false,
            seconds: 3,
            $imgUrl: this.$imgUrl,
        }
    },
    watch: {
        list() {
            setTimeout(() => {
                this.setList()
            }, 100)
        }
    },
    created() {
        // 状态栏改为黑色模式
        uni.setNavigationBarColor({
            frontColor: "#000000", //文字颜色
            backgroundColor: "#ffffff" //底部背景色
        })
        // 获取定位城市
        uni.getStorage({
            key: 'citName',
            success: (res) => {
                this.position = res.data
            }
        });
        //获取存储的最近访问
        uni.getStorage({
            key: 'location_key',
            success: (res) => {
                this.cacheLocation = res.data
            }
        });
        this.scrollHeight = uni.getSystemInfoSync().windowHeight - parseInt(this.CustomBar) + 'px'
        // that.getWarpweft()

        this.getCityList()
    },
    methods: {
        getCityList() {
            let eng = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'];
            let cityList = this.cityList;
            eng.forEach((ele, index) => {
                this.letter.push({ idx: ele });
                this.list.push({
                    idx: ele,
                    cities: []
                })
                for (var i = 0; i < cityList.length; i++) {
                    if (cityList[i].pinYin.slice(0, 1).toUpperCase() == ele) {
                        this.list[index].cities.push(cityList[i])
                    }
                }
            });
        },
        setList() {
            uni.createSelectorQuery()
                .in(this)
                .select('#list')
                .boundingClientRect()
                .exec(ret => {
                    this.winOffsetY = ret[0].top
                    this.winHeight = ret[0].height
                    this.itemHeight = this.winHeight / this.list.length
                })
        },
        touchStart(e) {
            this.touchmove = true
            let pageY = e.touches[0].pageY
            let index = Math.floor((pageY - this.winOffsetY) / this.itemHeight)
            if (this.list[index]) {
                this.scrollIntoId = this.list[index].idx
            }
        },
        touchMove(e) {
            let pageY = e.touches[0].pageY
            let index = Math.floor((pageY - this.winOffsetY) / this.itemHeight)
            if (this.list[index] && this.list[index].idx === this.scrollIntoId) {
                return false
            }
            if (this.list[index]) {
                this.scrollIntoId = this.list[index].idx
            }
        },
        touchEnd() {
            this.touchmove = false
            this.touchmoveIndex = -1
        },

        doneInput() {
            uni.hideKeyboard()
        },
        move(e) {
            console.log(e);
        },
        getId(index) {
            return this.letter[index];
        },
        query(source, text) {
            let res = [];
            var self = this;
            let len = source.length
            var text = text.toLowerCase()
            for (let i = 0; i < len; i++) {
                //单字母搜索
                if (text.length == 1 && /^[a-zA-Z]$/.test(text)) {
                    let arr = []
                    let idx = text.toUpperCase()
                    if (idx == source[i].idx) {
                        console.log(source[i]);
                        return source[i].cities
                    }
                }
                //其它搜索
                if (source[i].cities) {
                    let _len = source[i].cities.length
                    for (var n = 0; n < _len; n++) {
                        let _item = source[i].cities[n]
                        if (new RegExp('^' + text).test(_item.regionName)) {
                            res.push(_item);
                            continue;
                        }
                        if (new RegExp('^' + text).test(_item.pinYin)) {
                            res.push(_item);
                            continue;
                        }
                        if (new RegExp('^' + text).test(_item.py)) {
                            res.push(_item);
                            continue;
                        }

                    }
                }
            }

            return res;
        },

        isString(obj) {
            return typeof obj === 'string';
        },

        onInput(e) {
            const value = e.target.value;
            if (value !== '' && this.list) {
                const queryData = this.query(this.list, String(value).trim());
                this.searchList = queryData;
                this.disdingwei = false
            } else {
                this.searchList = [];
                this.disdingwei = true
            }
        },
        back() {
            if (this.position) {
                this.back_city(this.position, true)
            }
        },
        back_city(item) {
            if (item) {
                this.$emit('back_city', item);
                //unshift 把数据插入到首位，与push相反
                if (!this.cacheLocation) this.cacheLocation = []
                this.cacheLocation.unshift(item)
                this.searchValue = "";
                this.disdingwei = true
                var arr = this.cacheLocation
                //数组去重
                function distinct(arr) {
                    let newArr = []
                    for (let i = 0; i < arr.length; i++) {
                        if (newArr.indexOf(arr[i]) < 0) {
                            newArr.push(arr[i])
                        }
                    }
                    return newArr
                }
                this.cacheLocation = distinct(arr)
                uni.setStorage({
                    key: 'cacheLocation_key',
                    data: this.cacheLocation
                });
            } else {
                this.$emit('back_city', this.position);
            }

        },
        // 重新定位
        getWarpweft() {
            const that = this
            this.disabled = true
            // this.position = '请稍后'
            this.po_tips = '定位中...'
            let countdown = setInterval(() => {
                this.seconds--;
                uni.getLocation({
                    type: 'wgs84',
                    geocode: true,
                    success(res) {
                        uni.setStorageSync('latitude', res.latitude);
                        uni.setStorageSync('longitude', res.latitude);
                        that.getCity(res.latitude, res.longitude)
                        // this.po_tips = '重新定位'
                    }
                });
                if (this.seconds <= 0) {
                    this.seconds = 3
                    this.disabled = false
                    this.po_tips = '重新定位'
                    clearInterval(countdown);
                }
            }, 1000);
        },
        getCity(latitude, longitude) {
            qqmapsdk.reverseGeocoder({
                location: {
                    latitude,
                    longitude
                },
                success: function (res) {
                    this.position = res.result.address_component.city
                    this.disabled = false
                },
                fail(res) {
                    console.log(res, '报错了')
                    this.disabled = false
                },
            })
        },
    }
};
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f5f5;
  min-height: 100vh;
}
.fsmall {
  font-size: 26rpx;
}

.fmiddle {
  font-size: 28rpx;
}

.blue {
  color: #007aff;
}

.bold {
  font-weight: 600;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.mask {
  position: fixed;
  z-index: 3;
  top: 40%;
  left: 40%;
}

.mask-r {
  height: 200rpx;
  width: 200rpx;
  border-radius: 50%;
  display: flex;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
  justify-content: center;
  align-items: center;
  font-size: 80rpx;
  color: #ffffff;
}

.content {
  height: 100%;
  width: 100%;
  background-color: #ffffff;
}

.header {
  width: 100%;
  position: relative;
  z-index: 8;
  background-color: #ffffff;
}

.back_div {
  width: 100rpx;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.back_img {
  width: 35rpx;
  height: 35rpx;
}

.input {
  font-size: 26rpx;
  width: 600rpx;
  height: 60rpx;
  max-height: 60rpx;
  border-radius: 10rpx;
  background-color: #f5f5f5;
  padding-left: 20rpx;
  padding-right: 20rpx;
  box-sizing: border-box;
}

.title {
  font-size: 30rpx;
  color: white;
}

.show {
  left: 0;
  width: 100%;
  transition: left 0.3s ease;
}

.hide {
  left: 100%;
  width: 100%;
  transition: left 0.3s ease;
}

.title {
  font-size: 30rpx;
  color: white;
}

.letters {
  position: absolute;
  right: 0;
  width: 40rpx;
  color: #333333;
  top: 21%;
  text-align: center;
  font-size: 24rpx;
  font-weight: 510;
}

.letters .fmin {
  padding: 4rpx 10rpx;
}

.letter-header {
  font-size: 28rpx;
  padding-left: 40rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.city-div {
  width: 660rpx;
  margin: auto;
  padding: 20rpx 0;
  border-bottom-width: 0.5rpx;
  border-bottom-color: #ebedef;
  border-bottom-style: solid;
  display: flex;
  align-items: center;
}

.city {
  font-size: 28rpx;
  color: #000000;
  padding-left: 30rpx;
}

.dingwei {
  width: 90%;
  margin: auto;
  padding-top: 25rpx;
  box-sizing: border-box;
  margin-bottom: 26rpx;
}

.dingwei .grey {
  margin-bottom: 25rpx;
}

.dingwei_city {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  .blue {
    color: #999999;
    .refresh {
      width: 30rpx;
      height: 30rpx;
      margin-top: 2rpx;
    }
    text {
      padding-left: 14rpx;
    }
  }
}

.dingwei_city_one {
  height: 60rpx;
  background-color: #ffffff;
  border: 1rpx solid #dedede;
  border-radius: 8rpx;
  font-size: 26rpx;
  padding: 0 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 20rpx 20rpx 0;
  .dw {
    width: 25rpx;
    height: 28rpx;
    margin-right: 14rpx;
  }
}

.dingweis {
  width: 32rpx;
  height: 32rpx;
}

.dingwei_city_zuijin {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.footer {
  padding-top: 44rpx;
  color: #999999;
  font-size: 30rpx;
  text-align: center;
}
.map {
  // padding-top: var(--status-bar-height);
  background-color: #ffffff;
  .bar-top {
    background-color: #fff;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9999999;
  }
}
</style>
